#include <iostream>
#include <pthread.h>
#include "../socket.h"

void* sendMessage(void* socket) {
    Socket *sock = (Socket*)socket;

    std::string inFromKey;

    while(1) {
        getline(std::cin, inFromKey);
        std::cout << inFromKey << "\n";
        std::cout << ((*sock) << inFromKey) << "\n";
    }

    return socket;
}

void* receiveMessage(void* socket) {

    Socket *sock = (Socket*)socket;

    std::string inFromServer;
    while(1) {
        if(sock->receiveMessage(inFromServer) < 0) {
            std::cout << "Li " << (sock->receiveMessage(inFromServer)) << "bytes\n";
            std::cout << inFromServer;
        }
    }
    return socket;
}


int main(int argc, char *argv[])
{
    Socket *client = new Socket();
    pthread_t sendThread, receiveThread;

    if(argc > 1)
        client->setUsername(argv[1]);


    client->connectSocket();
    std::cout << "Conectei no servidor..\n";

    client->sendMessage(client->getUsername());

    pthread_create(&receiveThread, NULL, receiveMessage, client);

    pthread_create(&sendThread, NULL, sendMessage, client);

    pthread_join(sendThread, NULL);
    pthread_join(receiveThread, NULL);
}
